package com.qfedu.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.pojo.Product;
import com.qfedu.edu.iotserver.mapper.ProductMapper;
import com.qfedu.edu.iotserver.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.service.IJwtService;
import com.qfedu.edu.utils.ProductKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private IJwtService iJwtService;

    @Autowired
    private ProductMapper productMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Product product, HttpServletRequest req) {
        //校验参数的合法性
        if (null == product || StringUtils.isEmpty(product.getName()) || null == product.getAreaCode()){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(), ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到这里，参数合法，可以进行业务逻辑处理
        //首先生成产品key
        product.setProductKey(ProductKeyUtils.getProductKey(product.getAreaCode()));

        //设置用户名，和产品key一样
        product.setUsername(ProductKeyUtils.getProductKey(product.getAreaCode()));

        //设置密码
        product.setPassword(UUID.randomUUID().toString().replace("-", "").trim());

        //接下来获取通过获取请求头中的token，从而获取用户id
        String token = req.getHeader("token");
        String userId = iJwtService.getUserId(token);
        //设置租户id
        product.setTenantId(userId);

        //插入数据
        productMapper.insert(product);
    }
}
